import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/auth'
const sidebarStatus = sessionStorage.getItem('sidebarStatus')

import { userLogin, getUserInfo } from '@/api/user'

export const useApp = defineStore('app', {
    state:() => {
        return {
            opened: sidebarStatus ? !!+Number(sidebarStatus) : true
        }
    },
    actions: {}
})

export const useUser = defineStore('user', {
    state: () => {
        return {
            token: getToken(),
            name: '',
            avatar: '',
            role: ''
        }
    },
    actions: {
        login(userInfo:any) {
            return new Promise((resolve, reject) => {
                userLogin(userInfo).then(res => {
                    this.token = res.data.accessToken
                    setToken(res.data.accessToken)
                    console.log(res);
                    resolve(res)
                }).catch(err => {
                    reject()
                    console.log(err);
                })
            })
        },
        async getUserInfo() {
            const res = await getUserInfo({token:this.token})
            if(res.code === 200) {
                this.name = res.data.name
                this.avatar = res.data.avatar
                return 'ok'
            } else {
                return Promise.reject('error')
            }
        },
        loginOut() {
            removeToken()
            this.token = ''
        }
    }
})